package com.martini.admin.aspect;

import com.martini.common.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author martini at 2021/10/11 10:12
 */
@Slf4j
@Aspect
public class ControllerAspect {

    @Pointcut("execution(* com.martini.admin.controller.*.*(..))")
    public void controllerPointcut() {}

    @Around("controllerPointcut()")
    public Object aroundController(ProceedingJoinPoint pjp) {
        ServletRequestAttributes requestAttributes =
                Objects.requireNonNull((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes.getRequest();
        StringBuffer requestUrl = request.getRequestURL();
        long start = System.currentTimeMillis();
        try {
            log.info("=================== 进入方法[{}] ===================", requestUrl);
            Object[] args = pjp.getArgs();
            log.info("))===> 方法参数：[{}]", args);
            return pjp.proceed(args);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return R.fail().setMsg(throwable.getMessage());
        } finally {
            log.info("=================== 结束方法[{}], 总耗时: [{}]ms ===================",
                    requestUrl, System.currentTimeMillis() - start);
        }
    }
}
